package com.app.teaware.bluetooth;


import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.BasisApp;
import com.app.teaware.bean.BleDeviceListBean;
import com.app.teaware.util.BluetoothUtils;
import com.app.teaware.view.MySwipeRefreshLayout;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleRssiCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.flyco.dialog.listener.OnBtnClickL;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import my.DialogUtils;
import my.LogUtil;
import my.MySharedPreferences;

public class SearchBlueToothActivityTwo extends BasisActivity {

    private BleDevice mBleDevice;
    //给按钮点击
    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 1000L;

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private static final String TAG = SearchBlueToothActivityTwo.class.getSimpleName();
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private final static int SEARCH_CODE = 0x123;

    private DeviceAdapter mDeviceAdapter;
    private DeviceAdapter mPairDeviceAdapter;

    @BindView(R.id.rv_device)
    RecyclerView rvDevice;
    @BindView(R.id.rv_pair_device)
    RecyclerView rvPairDevice;
    @BindView(R.id.switchBtn)
    SwitchButton switchBtn;
    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.swipe_refresh_layout)
    MySwipeRefreshLayout swipeRefreshLayout;
    MySharedPreferences mSp ;


    @Override
    public void initViews() {
        setContentView(R.layout.bluetooth_search_activity);
        mDeviceAdapter = new DeviceAdapter(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvDevice.setVerticalScrollBarEnabled(true);
        rvDevice.setLayoutManager(layoutManager);
        rvDevice.setAdapter(mDeviceAdapter);

        mPairDeviceAdapter = new DeviceAdapter(this);
        LinearLayoutManager layoutManagerTwo = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvPairDevice.setVerticalScrollBarEnabled(true);
        rvPairDevice.setLayoutManager(layoutManagerTwo);
        rvPairDevice.setAdapter(mPairDeviceAdapter);

        swipeRefreshLayout.setEnabled(false);
        switchBtn.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if(isChecked){
                    swipeRefreshLayout.setRefreshing(true);
                }else {
                    if(swipeRefreshLayout.isRefreshing()){
                        showLoading("搜索者，请勿重复点击");
                        return;
                    }
                }

                if (isChecked == true) {
                    blueToothIsOpen();
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    if(isLocation){
                        BleManager.getInstance().cancelScan();
                        mDeviceAdapter.allClear();
                        mDeviceAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

        setTitle("蓝牙");
        tvDeviceName.setText("" + bluetoothAdapter.getName());

        swipeRefreshLayout.setColorSchemeResources(R.color.base_blue, R.color.base_text_green, R.color.base_color_red);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               if(bluetoothAdapter.isEnabled()){
                   startScan();
               } else {
//                   swipeRefreshLayout.setEnabled(false);
                   switchBtn.setChecked(false);
                   showToast("请打开蓝牙");
               }
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mSp = new MySharedPreferences(this);
        setHistoryDeviceZone();
    }


    private void showConnectedDevice() {
        List<BleDevice> deviceList = BleManager.getInstance().getAllConnectedDevice();
        mDeviceAdapter.clearConnectedDevice();
        for (BleDevice bleDevice : deviceList) {
            BluetoothDevice bluetoothDevice = bleDevice.getDevice();
                mDeviceAdapter.addDevice(bleDevice);
        }
        mDeviceAdapter.notifyDataSetChanged();
    }


    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                mDeviceAdapter.clearScanDevice();
                mDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                BluetoothDevice bluetoothDevice = bleDevice.getDevice();

                mDeviceAdapter.addDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();

                dismissProgress();
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    void setHistoryDeviceZone() {
        List<BleDevice> bleDeviceList = BleDeviceListBean.getInstance().getBleDevices();
        mPairDeviceAdapter.setDeviceList(bleDeviceList);
        mPairDeviceAdapter.notifyDataSetChanged();

        if (mPairDeviceAdapter != null && mPairDeviceAdapter.getItemCount() > 0) {
            findViewById(R.id.view_history_device_zone).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.view_history_device_zone).setVisibility(View.GONE);
        }
    }

    private final int REQUEST_SERVER_CHOOSE = 14;

    public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.ViewHolder> {

        private Context context;
        private List<BleDevice> bleDeviceList;

        public DeviceAdapter(Context context) {
            this.context = context;
            bleDeviceList = new ArrayList<>();
        }

        public void setDeviceList(List<BleDevice> dataList) {
            bleDeviceList = dataList;
        }

        public void addDevice(BleDevice bleDevice) {
            removeDevice(bleDevice);
            bleDeviceList.add(bleDevice);
        }

        public void deleteDevice(BleDevice bleDevice) {
            removeDevice(bleDevice);
        }

        public void removeDevice(BleDevice bleDevice) {
            for (int i = 0; i < bleDeviceList.size(); i++) {
                BleDevice device = bleDeviceList.get(i);
                if (bleDevice.getKey().equals(device.getKey())) {
                    bleDeviceList.remove(i);
                }
            }
        }

        public void clearConnectedDevice() {
            for (int i = 0; i < bleDeviceList.size(); i++) {
                BleDevice device = bleDeviceList.get(i);
                if (BleManager.getInstance().isConnected(device)) {
                    bleDeviceList.remove(i);
                }
            }
        }

        public void clearScanDevice() {
            for (int i = 0; i < bleDeviceList.size(); i++) {
                BleDevice device = bleDeviceList.get(i);
                if (!BleManager.getInstance().isConnected(device)) {
                    bleDeviceList.remove(i);
                }
            }
        }

        public void clear() {
            clearConnectedDevice();
            clearScanDevice();
        }

        public void allClear() {
            bleDeviceList.removeAll(bleDeviceList);
        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.bluetoothsearch_list_item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        @Override
        public int getItemCount() {
            return bleDeviceList == null ? 0 : bleDeviceList.size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView device_name;
            @BindView(R.id.text_address)
            public TextView device_address;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            public void bind(int position) {
                BleDevice bleDevice = bleDeviceList.get(position);
                //设备名称
                String deviceName = bleDevice.getDevice().getName();
                device_name.setText(TextUtils.isEmpty(deviceName) ? "未知设备" : deviceName);
                String deviceAddress = bleDevice.getDevice().getAddress();
                device_address.setText("" + deviceAddress);
                list_item.setTag(bleDevice);
//                list_item.setOnLongClickListener();
            }

            @OnClick(R.id.list_item)
            public void onItemClick(View v) {
                BleDevice bleDevice = (BleDevice) v.getTag();
                mBleDevice = bleDevice;
                BleDeviceListBean.getInstance().getBleDevices().add(bleDevice);
                blueToothConnect();
            }

            @OnLongClick(R.id.list_item)
            public boolean onItemLongClick(View v) {
                BleDevice bleDevice = (BleDevice) v.getTag();
                new QMUIDialog.MessageDialogBuilder(mContext).setMessage("是否删除已配对的蓝牙设备？").addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }

                }).addAction(0, "是", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                            BleDeviceListBean.getInstance().deleteBleDevice(bleDevice);
                            swipeRefreshLayout.setEnabled(true);
                            blueToothIsOpen();
                             dialog.dismiss();
                    }
                }).create().show();
                return true;
            }
        }

    }


    /**
     * 判断蓝牙是否开启
     */
    private void blueToothIsOpen() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 判断手机是否支持蓝牙
        if (bluetoothAdapter == null) {
            showToast("设备不支持蓝牙");
            finish();
        }

        if (!bluetoothAdapter.isEnabled()) {
            //弹出对话框提示用户是后打开
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, SEARCH_CODE);
        }
        checkGPSIsOpen();
    }

    boolean isLocation = true;
    private void checkPermissions() {
        Acp.getInstance(this).request(new AcpOptions.Builder()
                        .setPermissions( Manifest.permission.ACCESS_FINE_LOCATION
                        ).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        startScan();
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        isLocation = false;
                        switchBtn.setChecked(false);
                        BasisApp.showToast(permissions.toString() + "权限拒绝");
                    }
                });
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    DialogUtils.DialogTwo(mContext, "", "当前手机扫描蓝牙需要打开定位功能。", "前往设置", "取消", new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                        }
                    }, null);
                } else {
                    startScan();
                }
                break;
        }
    }

    private static final int BAIDU_READ_PHONE_STATE = 100;//定位权限请求
    private static final int PRIVATE_CODE = 1315;//开启GPS权限
    static final String[] LOCATIONGPS = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE};
    private boolean checkGPSIsOpen() {
        LocationManager lm = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {//开了定位服务
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PERMISSION_GRANTED) {// 没有权限，申请权限。
                ActivityCompat.requestPermissions(this, LOCATIONGPS,
                        BAIDU_READ_PHONE_STATE);
            }else {
                startScan();
            }

        } else {
            showToast("系统检测到未开启GPS定位服务,请开启");
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, PRIVATE_CODE);
        }

        return ok;
    }

    @Override
    protected void onResume() {
        super.onResume();
        showConnectedDevice();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SEARCH_CODE) {
            checkPermissions();
        }
        if (requestCode == PRIVATE_CODE) {
            startScan();
        }
    }

    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_LOCATION:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    private void readRssi(BleDevice bleDevice) {
        BleManager.getInstance().readRssi(bleDevice, new BleRssiCallback() {
            @Override
            public void onRssiFailure(BleException exception) {
                Log.i(TAG, "onRssiFailure" + exception.toString());
            }

            @Override
            public void onRssiSuccess(int rssi) {
                Log.i(TAG, "onRssiSuccess: " + rssi);
            }
        });
    }

    private void setMtu(BleDevice bleDevice, int mtu) {
        BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
            @Override
            public void onSetMTUFailure(BleException exception) {
                Log.i(TAG, "onsetMTUFailure" + exception.toString());
            }

            @Override
            public void onMtuChanged(int mtu) {
                Log.i(TAG, "onMtuChanged: " + mtu);
            }
        });
    }

    QMUITipDialog mDialogLoading;
    //蓝牙连接
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void blueToothConnect() {
        if (mBleDevice == null) {
            showToast("请选择蓝牙设备");
            return;
        }

        mDialogLoading = new QMUITipDialog.Builder(mContext)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在连接设备")
                .create();
        mDialogLoading.setCancelable(false);
        mDialogLoading.show();
        BluetoothUtils.getInstance().connectDevice(mBleDevice,new BluetoothUtils.MyBleConnectListener() {
            @Override
            public void onSuccess(BleDevice bleDevice) {
                mDialogLoading.dismiss();
                showToast("蓝牙成功！");
                finish();
            }

            @Override
            public void onFailed(BleException exception) {
                mDialogLoading.dismiss();
//                showToast("蓝牙连接失败错误码：" + exception.toString());
                showToast("蓝牙连接失败,请手动关开蓝牙,再次连接！");
//                BleManager.getInstance().disconnectAllDevice();
//                BleManager.getInstance().destroy();

            }


            @Override
            public void onTimeout() {
                LogUtil.i("onFailed--蓝牙连接超时-->");
                mDialogLoading.dismiss();
                showToast("连接超时，请稍后重试");
            }
        });
    }


}
